package com.song.demo.webmvc.servlet;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * GPView就是前面所说的自定义模板解析引擎，其核心方法是render
 * 在render方法中完成对模板的渲染，最终返回浏览器能识别的字符串
 * 通过response输出
 */
public class GPView {
    public static final String default_context_type = "text/html;charset=UTF-8";

    private File viewFile;

    public GPView(File viewFile){
        this.viewFile= viewFile;
    }
    public String getContextType(){
        return default_context_type;
    }

    public void render(Map<String,?> model, HttpServletRequest request, HttpServletResponse resp) throws IOException {
        StringBuffer stringBuffer = new StringBuffer();
        RandomAccessFile ra = new RandomAccessFile(this.viewFile, "r");
        try{
            String line = null;
            while ( (line = ra.readLine()) != null){
                Pattern pattern = Pattern.compile("\\$\\{[^\\}]+\\}", Pattern.CASE_INSENSITIVE);
                Matcher matcher = pattern.matcher(line);
                while (matcher.find()){
                    String paramName = matcher.group();
                    paramName = paramName.replaceAll("\\$\\{|\\}","");
                    Object paramValue = model.get(paramName);
                    if (null == paramValue){
                        continue;
                    }
                    line = matcher.replaceFirst(makeStringForRegexExp(paramValue.toString()));
                    matcher = pattern.matcher(line);

                }
                stringBuffer.append(line);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ra.close();
        }
        //resp.setCharacterEncoding("utf-8");
        resp.setContentType(default_context_type);
        resp.getWriter().write(stringBuffer.toString());
    }
    //处理特殊字符
    public static String makeStringForRegexExp(String str){
        return str.replace("\\","\\\\")
                .replace("*","\\*");
    }

}
